package com.mall.cart.web.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.mall.cart.service.CartService;
import com.mall.manager.pojo.TbItem;
import com.mall.manager.pojo.TbUser;
import com.mall.manager.service.ItemService;
import com.mall.pojo.TaotaoResult;
import com.mall.sso.service.TokenService;
import com.mall.utils.CookieUtils;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Controller
public class CartController {

    @Reference(timeout = 10000000)
    private ItemService itemService;

    @Reference(timeout = 1000000)
    private CartService cartService;

    @Value("${cookie_expire}")
    private int cookie_expire;

    /**
     * 添加商品进购物车，然后将数据写会浏览器的cookie中
     * @param itemId
     * @param num
     * @param req
     * @param res
     * @return
     */
    @GetMapping("/cart/add/{itemId}")
    public String addItemsToCart(@PathVariable("itemId") long itemId, @RequestParam(value = "num",defaultValue = "1") int num
            , HttpServletRequest req, HttpServletResponse res){
        List<TbItem> cartList = getCartItemsListByCookie(req);

        //判断用户是否登录
        TbUser user = (TbUser) req.getAttribute("User");
        //已经登录将购物车信息放到服务端
        if (user != null){
            //保存购物车信息到服务端
            TaotaoResult taotaoResult = cartService.addItemToCart(user.getId(), itemId, num);
            return "cartSuccess";
        }

        //用户未登录放cookie中
        boolean flag = false;
        //判断商品是否已经在cookie中存在
        for (TbItem item : cartList) {
            if (item.getId() == itemId){
                flag = true;
                item.setNum(item.getNum() + 1);
                break;
            }
        }

        //商品不再cookie中添加该商品到商品列表
        if (!flag) {
            TbItem item = itemService.getItemById(itemId);
            //设置商品数量,复用itemPojo中的属性
            item.setNum(num);
            cartList.add(item);
        }
        //将该新的商品列表写会cookie中,注意需要转码
        CookieUtils.setCookie(req,res,"cart",JSONArray.toJSONString(cartList),cookie_expire,true);

        return "cartSuccess";
    }

    /**
     * 查询cookie中的加入购物车的item信息
     * @param req
     */
    private List<TbItem> getCartItemsListByCookie(HttpServletRequest req) {
        //如果含有中文的信息到服务端需要进行解码
        String itemListJsonStr = CookieUtils.getCookieValue(req, "cart", true);
        if (StringUtils.isEmpty(itemListJsonStr)) {
            return new ArrayList<>();
        }
        List<TbItem> items = JSONArray.parseArray(itemListJsonStr, TbItem.class);
        return items;
    }


    /**
     * 展示购物车列表
     * @param req
     * @return
     */
    @GetMapping("cart/cart")
    public String showCart(HttpServletRequest req, Model model,HttpServletResponse res){

        List<TbItem> cartItems = getCartItemsListByCookie(req);

        //判断用户是否登录，如果已登录从redis中获取用户购物车数据
        TbUser user = (TbUser) req.getAttribute("User");
        if (user != null){
            //将cookie中的商品和server中的上品列表合并
            cartService.mergeItems(cartItems,user.getId().longValue());
            //删除cookie中购物车的信息
            CookieUtils.deleteCookie(req,res,"cart");
            //从服务端查购物车列表
            List<TbItem> serverCartList = cartService.showCart(user.getId());

            //返回视图需要展示的数据
            model.addAttribute("cartList",serverCartList);

            return "cart";
        }

        //用户未登录
        model.addAttribute("cartList",cartItems);
        return "cart";
    }


    /**
     * 当购物车中的商品修改后发送ajax请求修改cookie中购物车商品的信息
     * @param itemId
     * @param num
     * @return
     */
    @PostMapping("/cart/update/num/{itemId}/{num}")
    @ResponseBody
    public TaotaoResult updateCart(@PathVariable("itemId") long itemId, @PathVariable("num") int num,
                                   HttpServletRequest req, HttpServletResponse res){
        List<TbItem> cartList = getCartItemsListByCookie(req);

        TbUser user = (TbUser) req.getAttribute("User");
        //登录状态
        if (user != null){
            //更新服务端购物车数据
            cartService.updateCart(user.getId(),itemId,num);
            return TaotaoResult.ok();
        }
        //未登录状态
        for (TbItem item : cartList) {
            if (item.getId() == itemId){
                item.setNum(num);
                break;
            }
        }
        //将cartList重新写会cookie
        CookieUtils.setCookie(req,res,"cart",JSONArray.toJSONString(cartList),cookie_expire,true);

        return TaotaoResult.ok();
    }

    /**
     * 删除购物车商品
     * @param itemId
     * @param req
     * @param res
     * @return
     */
    @GetMapping("/cart/delete/{itemId}")
    public String deleteCartItem(@PathVariable("itemId") long itemId
            ,HttpServletRequest req,HttpServletResponse res){
        List<TbItem> cartList = getCartItemsListByCookie(req);

        TbUser user = (TbUser) req.getAttribute("User");

        //登录状态
        if (user != null) {
            //删除服务端指定购物车item的数据
            cartService.deleteCartItem(user.getId(),itemId);

            return "redirect:/cart/cart";
        }

        //未等登录状态
        for (TbItem item : cartList) {
            if (item.getId() == itemId){
                cartList.remove(item);
                break;
            }
        }
        //
        CookieUtils.setCookie(req,res,"cart",JSONArray.toJSONString(cartList),cookie_expire,true);
        //重定向到展示购物车商品路径
        return "redirect:/cart/cart";
    }

}
